/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
	AppRegistry,
	StyleSheet,
	Text,
	View,
	ListView,
	ScrollView,
	TouchableOpacity,
	TouchableHighlight,
	Dimensions,
	Image,
	Alert,
	Modal,
	NativeAppEventEmitter,
	Platform,
	BackAndroid,
	DeviceEventEmitter
} from 'react-native';

var Header = require("./Component/Header");
var Dialog = require("./Component/Dialog");
var _navigator;
var blestatus;
var base64 = require('base64-js');


import BleManager from 'react-native-ble-manager';

var scan_timer;
var listdata = [];

class DeviceList extends Component {
	
	constructor(props){
		super(props);
		_navigator = this.props.navigator;
		
		//listdata.push("123");
		var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
        	dataSource1: ds,
            dataSource: ds.cloneWithRows([{'image':'./image/devices/bra.png','title':"智能按摩内衣琳娜菲娅系列",'s_title':"随时可以做按摩的内衣"}
            	,{'image':'./image/devices/bra.png','title':"智能按摩内衣Idolly系列",'s_title':"随时可以做按摩的内衣"}]),
			modalVisible:false,
			mode:0
        };
        
//        this._setModalVisible = this._setModalVisible.bind(this);
        this._pressRow = this._pressRow.bind(this);
	}

	componentWillUnmount(){
		NativeAppEventEmitter
			.removeListener('BleManagerStopScan',this.handleStopScan);
			
      	NativeAppEventEmitter
          	.removeListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral);
          	
      	clearTimeout(scan_timer);
	}
				
	componentDidMount() {
		//ble相关监听函数
		this.handleStopScan = this.handleStopScan.bind(this);
		NativeAppEventEmitter
			.addListener('BleManagerStopScan',this.handleStopScan);
			
		this.handleDiscoverPeripheral = this.handleDiscoverPeripheral.bind(this);
      	NativeAppEventEmitter
           .addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral);

    }
	
		
	handleStopScan(data){
		this.setState({title:"扫描完成"});
	}
		
	checkblestatus(data){
 		console.log(data.state);
   	}
	
	handleDiscoverPeripheral(data){
       	if(data.name == null)
       		return;
       		
       	scan_timer = setTimeout(function(){
       		BleManager.stopScan();
       	},5000);
       	
       	if(this.state.mode == 0){
	       	if(data.name.substr(0,4) == "Kbra" && data.rssi >= -70)
	        {
	        	type = base64.toByteArray(data.advertising.data);
	        	var obj = {name:data.name,id:data.id};
				if(this.contain(listdata,obj) == 0){
	      			listdata.push(obj);
	        	
	        		this.setState({dataSource1: this.state.dataSource1.cloneWithRows(listdata)});
	        	}
	        }
     	}else if(this.state.mode == 1){
       		if(data.name.substr(0,6) == "IDOLLY" && data.rssi >= -70)
	        {
	        	type = base64.toByteArray(data.advertising.data);
	        	console.log(type[23].toString(16));
	        	var obj = {name:data.name+'_'+type[22].toString(16)+type[23].toString(16),id:data.id};
	        	if(this.contain(listdata,obj) == 0){
	      			listdata.push(obj);
	        	
	        		this.setState({dataSource1: this.state.dataSource1.cloneWithRows(listdata)});
	        	}
	        }
       	}
    }
	
	contain(list,obj){
		var i;
		for(i=0; i<list.length; i++){
			if(list[i].name === obj.name)
				return 1;
		}
		return 0;
	}

	_pressRow(rowID){
		
		this.setState({mode:rowID});
		this._setModalVisible(true);
	}
	
	_pressList(rowData){
		this._setModalVisible(false);
		DeviceEventEmitter.emit('changeAvatar',rowData);
		_navigator.pop();
	}
	
	_setModalVisible(visible) {
		
		if(visible){
			
			this.setState({title:"正在扫描设备"});
			BleManager.scan([], 5, true)
	            .then((results) => {console.log('Scanning...'); });
		}else{
			listdata = [];
			BleManager.stopScan();
			this.setState({dataSource1:this.state.dataSource1.cloneWithRows(listdata)});
		}
		this.setState({modalVisible:visible});
  	}

  	_setAnimationType(type) {
    	this.setState({animationType: type});
  	}

  	_toggleTransparent() {
    	this.setState({transparent: !this.state.transparent});
  	}

	_renderRow(rowData, sectionID, rowID){
		console.log(rowData.title);
        return (
        	<TouchableOpacity onPress={()=>this._pressRow(rowID)}>
			    <View style={styles.devices}>
			      	<Image source={require('./image/devices/bra.png')} style={{width:80,height:80,marginLeft:20}}/>
			      	<View style={{marginLeft:20,justifyContent: 'center',}}>
			      		<Text style={{fontSize:14}}>{rowData.title}</Text>
			      		<Text style={{fontSize:10,color:'#AAAAAA'}}>{rowData.s_title}</Text>
			      	</View>
			    </View>
			    
		    </TouchableOpacity>
        ); 
    }
	 
  	render() {
    	return (
      		<View style={styles.container}>
		      	<ScrollView>
		      		<Header name="添加设备" IconLeft="chevron-left" onPressLeft={()=> _navigator.pop()}/>
		      		<ListView 
		      			enableEmptySections = {true}
		      			dataSource={this.state.dataSource}
		      			renderRow={this._renderRow.bind(this)}/>
		      		<Dialog 
		      			title={this.state.title}
		      			_pressRow={this._pressList.bind(this)}
		      			dataSource={this.state.dataSource1} 
		      			modalVisible={this.state.modalVisible} 
		      			onPressBtn={()=>this._setModalVisible(false)}/>
		        </ScrollView>
      		</View>
    	);
  	}
}

const styles = StyleSheet.create({
	
	bgImage:{
		width:Dimensions.get('window').width,
		height:Dimensions.get('window').height
	},
  	container: {
    	flex: 1,
    	justifyContent: 'center',
    	alignItems: 'center',
    	backgroundColor: '#FAF4FF',
  	},
  	row: {
    	flex: 1,
    	justifyContent: 'center',
    	alignItems: 'center',
  	},
  	welcome: {
    	fontSize: 20,
    	textAlign: 'center',
    	margin: 10,
  	},
  	instructions: {
    	textAlign: 'center',
    	color: '#333333',
    	marginBottom: 5,
  	},
  	devices:{
  		width:Dimensions.get('window').width-20,
  		marginLeft:10,
  		height:130,
  		borderBottomWidth:1,
		borderBottomColor:"#A2B5CD",
  		marginRight:20,
    	alignItems: 'center',
    	flexDirection:'row',
  	},
});

module.exports = DeviceList;
